import { defineStore } from 'pinia'

const DEFAULT_PRODUCTS = [
  {
    id: 1,
    name: '红富士苹果',
    category: '水果',
    unit: 'kg',
    price: 8.5,
    minStock: 100,
    supplier: '北京水果批发市场',
    stockInfo: [
      { warehouse: '北京仓库', currentStock: 80, minStock: 100, status: '库存不足' },
      { warehouse: '上海仓库', currentStock: 120, minStock: 100, status: '正常' },
      { warehouse: '广州仓库', currentStock: 90, minStock: 100, status: '库存不足' }
    ]
  },
  {
    id: 2,
    name: '香蕉',
    category: '水果',
    unit: 'kg',
    price: 4.5,
    minStock: 100,
    supplier: '广州水果批发市场',
    stockInfo: [
      { warehouse: '北京仓库', currentStock: 150, minStock: 100, status: '正常' },
      { warehouse: '上海仓库', currentStock: 70, minStock: 100, status: '库存不足' },
      { warehouse: '广州仓库', currentStock: 200, minStock: 100, status: '正常' }
    ]
  },
  {
    id: 3,
    name: '新鲜生菜',
    category: '蔬菜',
    unit: 'kg',
    price: 3.5,
    minStock: 50,
    supplier: '上海蔬菜批发市场',
    stockInfo: [
      { warehouse: '北京仓库', currentStock: 30, minStock: 50, status: '库存不足' },
      { warehouse: '上海仓库', currentStock: 60, minStock: 50, status: '正常' },
      { warehouse: '广州仓库', currentStock: 40, minStock: 50, status: '库存不足' }
    ]
  }
]

export const useProductStore = defineStore('productStore', {
  state: () => ({
    products: [],
    initialized: false
  }),
  
  actions: {
    initialize() {
      if (!this.initialized) {
        const storedProducts = localStorage.getItem('products')
        this.products = storedProducts ? JSON.parse(storedProducts) : DEFAULT_PRODUCTS
        if (!storedProducts) {
          this.persist()
        }
        this.initialized = true
      }
    },

    setProducts(products) {
      this.products = products
      this.persist()
    },

    addProduct(product) {
      this.products.push(product)
      this.persist()
    },

    updateProduct(updated) {
      const index = this.products.findIndex(p => p.id === updated.id)
      if (index !== -1) {
        this.products[index] = { ...updated }
        this.persist()
      }
    },

    deleteProduct(id) {
      this.products = this.products.filter(p => p.id !== id)
      this.persist()
    },

    persist() {
      localStorage.setItem('products', JSON.stringify(this.products))
    }
  }
})
